package com.bestv.search.spider.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class StringUtil {

    public static String convertToJSONArrayText(String str) {
        str = str.substring(str.indexOf(SpiderConst.RIGHT_SQUARE_BRACKET));
        return str.substring(0, str.lastIndexOf(SpiderConst.LEFT_SQUARE_BRACKET) + 1);
    }

    public static String convertToURLEncoder(String str, String encoding) {
        try {
            return URLEncoder.encode(str, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static StringBuffer buildBuffer(String[] paras) {
        StringBuffer buffer = new StringBuffer();
        for (String para : paras) {
            buffer.append(para);
        }
        return buffer;
    }

    public static StringBuffer buildBuffer(String[] paras, String split) {
        StringBuffer buffer = new StringBuffer();
        if (paras != null && paras.length > 0) {
            for (int i = 0; i < paras.length; i++) {
                buffer.append(paras[i]);
                if (i != paras.length - 1) {
                    buffer.append(split);
                }
            }
        }
        return buffer;
    }

    // Unicode to native
    public static String ascii2Native(String str) {
        StringBuilder sb = new StringBuilder();
        int begin = 0;
        int index = str.indexOf(SpiderConst.CHAR_U);
        while (index != -1) {
            sb.append(str.substring(begin, index));
            if (str.length() - 1 >= index + 6) {
                sb.append(ascii2Char(str.substring(index, index + 6)));
                begin = index + 6;
                index = str.indexOf(SpiderConst.CHAR_U, begin);
            } else {
                break;
            }
        }
        sb.append(str.substring(begin));
        return sb.toString();
    }

    private static char ascii2Char(String str) {
        int code = 0;
        try {
            if (str.length() != 6) {
                throw new IllegalArgumentException("Ascii string of a native character must be 6 character.");
            }
            if (!SpiderConst.CHAR_U.equals(str.substring(0, 2))) {
                throw new IllegalArgumentException("Ascii string of a native character must start with "
                        + SpiderConst.CHAR_U);
            }
            String tmp = str.substring(2, 4);
            code = Integer.parseInt(tmp, 16) << 8;
            tmp = str.substring(4, 6);
            code += Integer.parseInt(tmp, 16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (char) code;
    }
}
